package com.flyduck.vueshop.common.core.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.flyduck.vueshop.common.core.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @program: vueshop
 * @description:
 * @author: flyduck
 * @create: 2024-05-07 21:13
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BusinessException.class)
    public Result<Void> handler(BusinessException e){
        log.error("业务异常", e);
        return Result.fail(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(value = BindException.class)
    public Result<Void> handler(BindException e){
        log.error("实体校验异常", e);
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return Result.fail(objectError.getDefaultMessage());
    }

    /*sa-token异常*/
    @ExceptionHandler(value = NotLoginException.class)
    public Result<Void> handler(NotLoginException e){
        log.error("未登录异常", e);
        return Result.fail(401,"请先登录");
    }

    @ExceptionHandler(value = NotPermissionException.class)
    public Result<Void> handler(NotPermissionException e){
        log.error("没有权限异常", e);
        return Result.fail(403,"无权限操作");
    }
    /*sa-token异常*/

    @ExceptionHandler(value = RuntimeException.class)
    public Result<Void> handler(RuntimeException e){
        log.error("系统异常", e);
        return Result.fail(e.getMessage());
    }
}
